package com.xiongjie.SingleCache;

import com.xiongjie.SingleCache.Interface.ISingleCache;
import com.xiongjie.SingleCache.entity.SingleCacheEntity;
import com.xiongjie.SingleCache.service.SSingleCacheService;
import com.xiongjie.SingleCache.service.RSingleCacheService;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;

import java.util.concurrent.TimeUnit;

public class SingleCacheApplication {

   static final String[] names = {"Rome","Como","Basel","Bern","London","Newcastle","Bucarest"};

   private final EmbeddedCacheManager cacheManager;
   private final ISingleCache iSingleCache;
   private Cache<String, SingleCacheEntity> cache;

   /**
    * 构造函数，创建缓存管理器和接口实现类
    */
   public SingleCacheApplication() {

      //自定义缓存并设置过期时间
      cacheManager = new DefaultCacheManager();
      ConfigurationBuilder config = new ConfigurationBuilder();
      config.expiration().lifespan(1, TimeUnit.MINUTES);
      cacheManager.defineConfiguration("singleCache", config.build());
      cache = cacheManager.getCache("singleCache");

      iSingleCache = initSingleCacheService(cache);
   }

   /**
    * 销毁缓存管理器
    */
   public void shutdown() {
      cacheManager.stop();
   }

   /**
    * 初始化接口实现类，重要的数据，在系统环境变量中设置
    * @param cache
    * @return
    */
   private ISingleCache initSingleCacheService(Cache<String, SingleCacheEntity> cache) {
      String apiKey = System.getenv("APIKEY");
      if (apiKey == null) {
         System.out.println("警告: APIKEY 环境变量没有设置,使用RSingleCacheService");
         return new RSingleCacheService(cache);
      } else {
         return new SSingleCacheService(apiKey, cache);
      }
   }

   /**
    * 父类引用调用子类对象
    */
   public void getSingleCacheEntity() {
      System.out.println("获取单机缓存实体数据");

      long start = System.currentTimeMillis();

      for (String name : names) {
         SingleCacheEntity entity = iSingleCache.getValueByName(name);
         System.out.println(String.format("%s - %s", name, entity));
      }

      System.out.println(String.format("获取单机缓存实体数据花费时间：%dms", System.currentTimeMillis() - start));
   }

   public static void main(String[] args) throws Exception {

      SingleCacheApplication app = new SingleCacheApplication();

      app.getSingleCacheEntity();
      app.getSingleCacheEntity();

      TimeUnit.SECONDS.sleep(5);

      app.getSingleCacheEntity();
      app.shutdown();
   }

}
